package com.example.spring_boot_demo.controller;

import org.apache.catalina.connector.RequestFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "userServlet", urlPatterns = "/user/*")
public class UserServlet extends HttpServlet {

    private static final Logger log = LoggerFactory.getLogger(UserServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }
    //
    /**
     * http://localhost:8099/user/test2
     * http://localhost:8099/user/StringValue
     * 根据url来判断 调用当前请求需要处理的方法
     *
     */
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //resp
        RequestFacade requestFacade = (RequestFacade) req;
            String uri = requestFacade.getRequestURI();
        String url = requestFacade.getRequestURL().toString();
        //http://localhost:8081/user/test2
        log.info("当前访问的uri是：{}", uri);
        log.info("当前访问的 url 是：{}", url);
        if (uri.contains("StringValue")) {
            stringValue(req, resp);
        } else if (uri.endsWith("test2")) {
            test2(req, resp);

        } else {
            resp.getWriter().print("404");
            resp.getWriter().flush();
            resp.getWriter().close();
        }

    }

    private void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().print("处理 test2 的请求");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    private void stringValue(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        RequestFacade requestFacade = (RequestFacade) req;
        String name = requestFacade.getParameter("name");
        log.info("name:{}", name);
        resp.getWriter().print("处理 stringValue 的请求");
        resp.getWriter().flush();
        resp.getWriter().close();
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }


}
